import dayjs from "dayjs";
import Detail from "./detail.vue";
import { message } from "@/utils/message";
import type { PaginationProps } from "@pureadmin/table";
import { addDialog } from "@/components/ReDialog";
import { useCopyToClipboard } from "@pureadmin/utils";
import { getOperationLogsList, getOperationLogsDetail } from "@/api/system";
import Info from "@iconify-icons/ri/question-line";
import type { OperationLogItem } from "./types";
import { usePublicHooks } from "@/views/system/hooks";
export function useOperation(tableRef: Ref) {
  const form = reactive({
    userName: "",
    requestTime: ""
  });
  const dataList = ref([]);
  const loading = ref(true);
  const selectedNum = ref(0);
  const { copied, update } = useCopyToClipboard();
  const { tagStyle } = usePublicHooks();

  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 15,
    currentPage: 1,
    pageSizes: [15, 30, 50, 100],
    background: true
  });

  const columns: TableColumnList = [
    {
      headerRenderer: () => (
        <span class="flex-c">
          请求接口
          <iconifyIconOffline
            icon={Info}
            class="ml-1 cursor-help"
            v-tippy={{
              content: "双击下面请求接口进行拷贝"
            }}
          />
        </span>
      ),
      prop: "apiPath",
      minWidth: 140
    },
    {
      label: "请求方法",
      prop: "method",
      minWidth: 140
    },
    {
      label: "IP 地址",
      prop: "ipAddress",
      minWidth: 100
    },
    {
      label: "地点",
      prop: "location",
      minWidth: 140
    },
    {
      label: "操作系统",
      prop: "os",
      minWidth: 100
    },
    {
      label: "浏览器类型",
      prop: "browser",
      minWidth: 100
    },
    {
      label: "操作状态",
      minWidth: 100,
      cellRenderer: ({ row, props }) => (
        <el-tag size={props.size} style={tagStyle.value(row.status)}>
          {row.status ? "成功" : "失败"}
        </el-tag>
      )
    },
    {
      label: "请求耗时",
      prop: "duration",
      minWidth: 100,
      cellRenderer: ({ row, props }) => (
        <el-tag
          size={props.size}
          type={row.duration < 1000 ? "success" : "warning"}
          effect="plain"
        >
          {row.duration} ms
        </el-tag>
      )
    },
    {
      label: "请求时间",
      minWidth: 180,
      formatter: ({ requestTime }) =>
        dayjs(requestTime).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: "操作",
      fixed: "right",
      slot: "operation"
    }
  ];

  function handleSizeChange(val: number) {
    pagination.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  /** 取消选择 */
  function onSelectionCancel() {
    selectedNum.value = 0;
    // 用于多选表格，清空用户的选择
    tableRef.value.getTableRef().clearSelection();
  }

  /** 拷贝请求接口，表格单元格被双击时触发 */
  function handleCellDblclick({ apiPath }, { property }) {
    if (property !== "apiPath") return;
    update(apiPath);
    copied.value
      ? message(`${apiPath} 已拷贝`, { type: "success" })
      : message("拷贝失败", { type: "warning" });
  }
  function onDetail(logData: OperationLogItem) {
    getOperationLogsDetail({
      id: logData.id
    }).then(res => {
      res["pureUser.userName"] = logData.pureUser.userName;
      res["_requestTime"] = dayjs(res.requestTime).format(
        "YYYY-MM-DD HH:mm:ss"
      );
      res["_status"] = res.status ? "成功" : "失败";
      addDialog({
        title: "操作日志详情",
        fullscreen: true,
        hideFooter: true,
        contentRenderer: () => Detail,
        props: { data: [res] }
      });
    });
  }

  function onSearch() {
    loading.value = true;
    getOperationLogsList({
      ...form,
      pageSize: pagination.pageSize,
      currentPage: pagination.currentPage
    })
      .then(data => {
        dataList.value = data.list;
        pagination.total = data.total;
        pagination.pageSize = data.pageSize;
        pagination.currentPage = data.currentPage;
      })
      .finally(() => {
        loading.value = false;
      });
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  onMounted(() => {
    onSearch();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    pagination,
    selectedNum,
    onSearch,
    onDetail,
    resetForm,
    handleSizeChange,
    onSelectionCancel,
    handleCellDblclick,
    handleCurrentChange
  };
}
